<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    width="50%"
    :maskClosable="false"
    :title="t(`common.title.${type}`)"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
    <table
      v-show="Noadd"
      align="center"
      border="1"
      class="tableName"
      cellpadding="10"
      cellspacing="5"
    >
      <thead>
        <tr>
          <th>文件名称</th>
          <th>上传时间</th>
          <th>预览材料</th>
          <th v-show="!NoUPload">删除材料</th>
          <!-- v-if="upLoadShow != '1' && state" -->
        </tr></thead
      >
      <tbody>
        <tr v-for="(item, value) in resultAll" :key="value">
          <td>{{ item.originalFileName }}</td>
          <td>{{ item.createdTime }}</td>
          <td>
            <a-button
              preIcon="ant-design:eye-filled"
              class="anniu anniu-first"
              @click="handleView(item.url)"
              >预览</a-button
            ></td
          >
          <td
            ><a-button
              preIcon="ant-design:delete-outlined"
              class="anniu"
              v-show="!NoUPload"
              @click="batchDelete(item.id)"
              >删除</a-button
            ></td
          >
        </tr>
      </tbody>
    </table>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, unref } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ActionEnum, VALIDATE_API } from '/@/enums/commonEnum';
  import { TsUploadDelete } from '/@/api/basic/qimo/index';
  import { getValidateRules } from '/@/api/lamp/common/formValidateService';
  import { editFormSchema } from './defUser.data';
  import { taskFeatureContribute, taskFeatureContributeput } from '/@/api/basic/qimo/index';
  export default defineComponent({
    name: 'DefUserEdit',
    components: { BasicDrawer, BasicForm },
    props: {
      foundId: {
        type: String as PropType<string>,
        required: true,
      },
    },
    emits: ['success', 'register'],
    setup(props, { emit }) {
      let Noadd = ref(false);
      let NoUPload = ref(false);
      let resultAll: any = ref();
      const { t } = useI18n();
      const type = ref<ActionEnum>(ActionEnum.ADD);
      const { createMessage } = useMessage();
      const [registerForm, { setFieldsValue, resetFields, updateSchema, validate, resetSchema }] =
        useForm({
          labelWidth: 230,
          schemas: editFormSchema(type),
          showActionButtonGroup: false,
          // disabled: (_) => {
          //   return unref(type) === ActionEnum.VIEW;
          // },
          baseColProps: { span: 24 },
          actionColOptions: {
            span: 23,
          },
        });
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        await resetSchema(editFormSchema(type));
        await resetFields();
        setDrawerProps({ confirmLoading: false });
        type.value = data?.type;

        if (unref(type) !== ActionEnum.ADD) {
          // 赋值
          if (unref(type) !== ActionEnum.EDIT) {
            NoUPload.value = true;
            console.log(NoUPload, '222222');
          } else {
            NoUPload.value = false;
          }
          Noadd.value = true;
          const record = { ...data?.record };
          resultAll.value = record.tfcmList;
          await setFieldsValue(record);
        } else {
          Noadd.value = false;
        }
        // if (unref(type) !== ActionEnum.VIEW) {
        //   let validateApi = Api[VALIDATE_API[unref(type)]];
        //   await getValidateRules(validateApi, customFormSchemaRules(type)).then(async (rules) => {
        //     rules && rules.length > 0 && (await updateSchema(rules));
        //   });
        // }
      });
      function setCurrentDate(): string {
        const currentDate = new Date();
        const year = currentDate.getFullYear();
        const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
        const day = currentDate.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
      }

      async function handleSubmit() {
        try {
          setDrawerProps({ confirmLoading: true });
          let alles = await validate();

          const alllist = props.foundId;
          // tenantId: props.foundId,
          const otherIds = {
            fillInDate: setCurrentDate(),
          };
          let params = { ...alles, ...otherIds };
          // params.push(otherIds);
          // params.collTenantIds = params.collTenantIds.filter((item) => !alllist.includes(item));
          if (params.collTenantIds != null) {
            params.collTenantIds = params.collTenantIds.filter((item) => !alllist.includes(item));
          }
          // if (unref(type) !== ActionEnum.VIEW) {
          if (unref(type) === ActionEnum.EDIT || unref(type) === ActionEnum.PingFEn) {
            // alert(unref(type));
            await taskFeatureContributeput(params);
          } else if (unref(type) === ActionEnum.ADD) {
            // alert(unref(type));
            await taskFeatureContribute(params);
          }
          createMessage.success(t(`common.tips.${type.value}Success`));
          // }
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }
      // 预览
      function handleView(value) {
        window.open(value, '_blank');
      }
      // 删除
      async function batchDelete(id: string[]) {
        const delId = [id];
        await TsUploadDelete(delId);
        createMessage.success(t('common.tips.deleteSuccess'));
        emit('success');
        closeDrawer();
      }
      return {
        batchDelete,
        handleView,
        Noadd,
        NoUPload,
        type,
        t,
        registerDrawer,
        registerForm,
        handleSubmit,
        setCurrentDate,
        resultAll,
      };
    },
  });
</script>
